package com.hk.core.web;

import com.hk.commons.util.ArrayUtils;
import com.hk.commons.util.StringEscapeHandler;
import jakarta.servlet.http.HttpServletRequest;


/**
 * @author kevin
 * @date 2018-06-07 17:19
 */
public class XssHttpServletRequestWrapper extends RepeatReadHttpServletRequestWrapper {

    private final StringEscapeHandler stringEscapeHandler;

    /**
     * Constructs a request object wrapping the given request.
     *
     * @param request The request to wrap
     * @throws IllegalArgumentException if the request is null
     */
    public XssHttpServletRequestWrapper(StringEscapeHandler stringEscapeHandler,
                                        HttpServletRequest request) {
        super(request);
        this.stringEscapeHandler = stringEscapeHandler;
    }

    @Override
    public String getQueryString() {
        return stringEscapeHandler.escape(super.getQueryString());
    }

    @Override
    public String getParameter(String name) {
        return stringEscapeHandler.escape(super.getParameter(name));
    }

    @Override
    public String[] getParameterValues(String name) {
        var parameters = super.getParameterValues(name);
        if (ArrayUtils.isEmpty(parameters)) {
            return null;
        }
        for (int i = 0, length = parameters.length; i < length; i++) {
            parameters[i] = stringEscapeHandler.escape(parameters[i]);
        }
        return parameters;
    }

    @Override
    public String getHeader(String name) {
        return stringEscapeHandler.escape(super.getHeader(name));
    }

    @Override
    protected String enhanceBody(String body) {
        return stringEscapeHandler.escape(super.enhanceBody(body));
    }
}
